const models = require('./db')
const express = require('express')
const router =express.Router()
//检查账号是否登录，自动登录
router.get('/api/check_login',(req,res)=>{
    if(req.session.loginUser){
      res.send({code:1,message:'已经登录'})
    }else{
      res.send({code:404,message:'请先登录！'})
    }
})
//账户登出
router.get('/api/logout',(req,res)=>{
  req.session.destroy(function(err){
    if(err){
      res.send({code:400,message:'登出失败'})
    }else{
      res.send({code:1,message:'登出成功'});
    }
  })
})
//注册账户
router.post('/api/login/createAccount',(req,res)=>{
    //创建模型
    let newAccount = new models.Login({
        account:req.query.account,
        password:req.query.password
    })
    //存入数据库
    newAccount.save((err,data)=>{
        if(err){
            res.send(err)
        }else{
            res.send('createAccount successed')
        }
    })
})
//登录查询账户密码
router.post('/api/login/getAccount',(req,res)=>{
     //console.log(req.signedCookies)
    //数据库查询
    models.Login.findOne({account:req.query.account},(err,data)=>{
        if(err){
            res.send(err)
        }else{
            if(data!=null&&data.password==req.query.password){
              //res.cookie('session','sessionId',{maxAge:900000,httpOnly:true,singed:true})
              req.session.loginUser = req.query.account;
              res.send({code:1,data:data,message:'操作成功'})
            }

            else
                res.send({code:404,message:'账号密码不正确，请重新输入'})
        }
    })
})
module.exports = router;
